package edu.upn.sigemfi.seg.bc;

import edu.upn.sigemfi.seg.be.Cargo;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

public class CargoDelegate {

    private CargoFacadeLocal local;

    public CargoDelegate() {
        local = lookupCargoFacade();
    }

    public void crear(Cargo cargo) throws Exception {
        try {
            local.create(cargo);
        } catch (Exception e) {
            local = lookupCargoFacade();
            throw new Exception("Crear Cargo. " + e.getMessage(), e);
        }
    }

    public void editar(Cargo cargo) throws Exception {
        try {
            local.edit(cargo);
        } catch (Exception e) {
            local = lookupCargoFacade();
            throw new Exception("Editar Cargo. " + e.getMessage(), e);
        }
    }

    public void eliminar(Cargo cargo) throws Exception {
        try {
            local.remove(cargo);
        } catch (Exception e) {
            local = lookupCargoFacade();
            throw new Exception("Eliminar Cargo. " + e.getMessage(), e);
        }
    }

    public Cargo buscar(Long codigo) throws Exception {
        try {
            return local.find(codigo);
        } catch (Exception e) {
            local = lookupCargoFacade();
            throw new Exception("Buscar Cargo. " + e.getMessage(), e);
        }
    }

    public List<Cargo> listar() throws Exception {
        try {
            return local.findAll();
        } catch (Exception e) {
            local = lookupCargoFacade();
            throw new Exception("Listar Agencias. " + e.getMessage(), e);
        }
    }

    private CargoFacadeLocal lookupCargoFacade() {
        try {
            Context c = new InitialContext();
            return (CargoFacadeLocal) c.lookup("java:comp/env/CargoFacade");
        } catch (NamingException ne) {
            Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", ne);
            throw new RuntimeException(ne);
        }
    }
}
